package com.softlab.retailwholesalesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.softlab.retailwholesalesystem.entity.OrderEntity;
import com.softlab.retailwholesalesystem.entity.OrderGoodsMapEntity;
import com.softlab.retailwholesalesystem.entity.StoreEntity;
import com.softlab.retailwholesalesystem.entity.VO.QuickEntity;
import com.softlab.retailwholesalesystem.mapper.OrderGoodsMapMapper;
import com.softlab.retailwholesalesystem.mapper.OrderMapper;
import com.softlab.retailwholesalesystem.mapper.StoreMapper;
import com.softlab.retailwholesalesystem.service.IGoodsService;
import com.softlab.retailwholesalesystem.service.IOrderService;
import com.softlab.retailwholesalesystem.service.exception.NoSuchStoreException;
import com.softlab.retailwholesalesystem.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;


@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderEntity> implements IOrderService {
    @Autowired
    private OrderMapper mapper;

    @Autowired
    private OrderGoodsMapMapper mapMapper;

    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private OrderGoodsMapService mapService;


    @Override
    public List<OrderEntity> searchOrders(OrderEntity order) {
        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete", 0);
        if (order.getOrderId() != null) wrapper.eq("order_id", order.getOrderId());
        if (order.getOrderType() != null) wrapper.eq("order_type", order.getOrderType());
        if (order.getOrderProfit() != null) wrapper.eq("order_profit", order.getOrderProfit());
        if (order.getClientName() != null) wrapper.eq("client_name", order.getClientName());
        if (order.getStatus() != null) wrapper.eq("status", order.getStatus());
        if (order.getUsername() != null) wrapper.eq("username", order.getUsername());
        if (order.getInOut() != null) wrapper.eq("in_out", order.getInOut());
        return mapper.selectList(wrapper);
    }

    @Override
    public Integer updateOrder(OrderEntity order) {
        String status = order.getStatus();
        if (status != null && (status.equals("待付款")))
            checkPass(order);
        return mapper.updateById(order);
    }

    public void checkPass(OrderEntity order) {
        order = mapper.selectById(order.getOrderId());
        QueryWrapper<OrderGoodsMapEntity> mapWrapper = new QueryWrapper<>();
        mapWrapper.eq("order_id", order.getOrderId());
        mapWrapper.eq("is_delete", 0);
        List<OrderGoodsMapEntity> mapEntityList = mapMapper.selectList(mapWrapper);
        for (OrderGoodsMapEntity map : mapEntityList) {
            QueryWrapper<StoreEntity> storeWrapper = new QueryWrapper<>();
            storeWrapper.eq("goods_id", map.getGoodsId())
                    .eq("repository_id", map.getRepositoryId())
                    .eq("is_delete", 0);
            StoreEntity store = storeMapper.selectOne(storeWrapper);
//            if (store == null) {
//                throw new NoSuchStoreException("无库存");
//            }

            System.err.println("order (inout)" + order);

            if (order.getInOut() == 1){
                if (store == null) {
                    throw new NoSuchStoreException("无库存");
                }
                Integer goodsNumber = store.getGoodsNumber();
                store.setGoodsNumber(goodsNumber - map.getGoodsNumber());
            } else{

                Integer goodsNumber = store.getGoodsNumber();
                store.setGoodsNumber(goodsNumber + map.getGoodsNumber());
            }

            if (store.getGoodsNumber() == 0)
                store.setIsDelete(1);
            storeMapper.updateById(store);
        }
    }

    private void setProfitAndTotalByMao(OrderGoodsMapEntity entity){
        QueryWrapper<OrderEntity> qw = new QueryWrapper<OrderEntity>().eq("order_id", entity.getOrderId());
        OrderEntity order = mapper.selectList(qw).get(0);
        setProfitAndTotalByType(order);
    }
    @Override
    public void setProfitAndTotalByType(OrderEntity order) {
        QueryWrapper<OrderGoodsMapEntity> mapWrapper = new QueryWrapper<>();
        mapWrapper.eq("order_id", order.getOrderId());
        mapWrapper.eq("is_delete", 0);
        List<OrderGoodsMapEntity> mapEntityList = mapMapper.selectList(mapWrapper);

        if (mapEntityList.isEmpty())
            return;


        Double profit = 0.0;
        Double total = 0.0;
        for (OrderGoodsMapEntity e :
                mapEntityList) {
            mapService.setSinglePriceByType(e);
            Double singlePrice = e.getSinglePrice();
            Integer goodsNumber = e.getGoodsNumber();
            Long goodsId = e.getGoodsId();

            Double stockPrice = goodsService.getById(goodsId).getStockPrice();

            Double singleProfit = singlePrice - stockPrice;

            profit += goodsNumber * singleProfit;
            total += goodsNumber * singlePrice;
        }

        if (order.getInOut() != null && order.getInOut() == 0) {
            order.setOrderProfit(0 - profit);
            order.setTotalPrice(0 - total);
        } else {
            order.setOrderProfit(profit);
            order.setTotalPrice(total);
        }

        mapper.updateById(order);
    }

    @Override
    public void init() {
        List<OrderEntity> entities = mapper.selectList(null);
        for (OrderEntity e :
                entities) {
            setProfitAndTotalByType(e);
            mapper.updateById(e);

        }
    }


    /**
     * 添加商品
     * @param order
     * @return
     */
    @Override
    public Integer confirm(OrderEntity order) {
        QueryWrapper<OrderGoodsMapEntity> mapWrapper = new QueryWrapper<>();
        mapWrapper.eq("order_id", order.getOrderId());
        mapWrapper.eq("is_delete", 0);
        List<OrderGoodsMapEntity> mapEntityList = mapMapper.selectList(mapWrapper);

        for (OrderGoodsMapEntity e :
                mapEntityList) {
           delStore(e);
        }
        return 200;//OK

    }

    /**
     * 退货商品
     * @param order
     * @return
     */
    @Override
    public Integer confirm2(OrderEntity order) {
        System.err.println("开始调用confirm2：");
        QueryWrapper<OrderGoodsMapEntity> mapWrapper = new QueryWrapper<>();
        mapWrapper.eq("order_id", order.getOrderId());
        mapWrapper.eq("is_delete", 0);
        List<OrderGoodsMapEntity> mapEntityList = mapMapper.selectList(mapWrapper);
        System.err.println("mapList:" + mapEntityList);


        for (OrderGoodsMapEntity e :
                mapEntityList) {
            System.err.println("开始调用addStore():");
            addStore(e);
        }

        return 200;//OK

    }

    @Override
    public QuickEntity saveQuick(QuickEntity quick) {
        OrderEntity order = new OrderEntity();
        order.setOrderType("newQuick");
        mapper.insert(order);

        QueryWrapper<OrderEntity> orderEntityQueryWrapper = new QueryWrapper<>();
        orderEntityQueryWrapper.eq("order_type", "newQuick");
        OrderEntity orderEntity = mapper.selectList(orderEntityQueryWrapper).get(0);

        quick.getOrder().setOrderId(orderEntity.getOrderId());
        quick.getOrder().setInOut(1);
        quick.getOrder().setIsDelete(0);

        setProfitAndTotalByType(quick.getOrder());
        mapper.updateById(quick.getOrder());
        return quick;
    }

    @Override
    public Long addQuickGoods(OrderGoodsMapEntity entity){
        OrderGoodsMapEntity newEntity = new OrderGoodsMapEntity();
        newEntity.setIsDelete(-1);
        mapMapper.insert(newEntity);
        QueryWrapper<OrderGoodsMapEntity> qw = new QueryWrapper<>();
        qw.eq("is_delete", "-1");
        OrderGoodsMapEntity currEntity = mapMapper.selectList(qw).get(0);
        entity.setMapId(currEntity.getMapId());
        entity.setIsDelete(0);
        mapMapper.updateById(entity);

        delStore(entity);
        setProfitAndTotalByMao(entity);

        return entity.getMapId();
    }

    @Override
    public Integer delQuickGoods(Long id){
        OrderGoodsMapEntity orderGoodsMapEntity = mapMapper.selectById(id);

        addStore(orderGoodsMapEntity);
        orderGoodsMapEntity.setIsDelete(0);
        mapMapper.updateById(orderGoodsMapEntity);

        setProfitAndTotalByMao(orderGoodsMapEntity);

        return 200;
    }

    /**
     * 根据map修改仓库
     * @param e
     * @return
     */
    private Integer delStore(OrderGoodsMapEntity e){
        Integer goodsNumber = e.getGoodsNumber();
        Long goodsId = e.getGoodsId();
        Integer repositoryId = e.getRepositoryId();

        QueryWrapper<StoreEntity> storeWrapper = new QueryWrapper<>();
        storeWrapper.eq("goods_id", goodsId);
        storeWrapper.eq("repository_id", repositoryId);
        storeWrapper.eq("is_delete", 0);
        StoreEntity storeEntity = storeMapper.selectOne(storeWrapper);

        if (storeEntity == null)
            return 404;//没有找到这条记录

        if (storeEntity.getGoodsNumber() < goodsNumber)
            return 500; //库存不够

        storeEntity.setGoodsNumber(storeEntity.getGoodsNumber() - goodsNumber);

        if (storeEntity.getGoodsNumber() == 0)
            storeEntity.setIsDelete(1);
        storeMapper.updateById(storeEntity);
        return 200;
    }

    /**
     * 根据map修改仓库
     * @param e
     * @return
     */
    private Integer addStore(OrderGoodsMapEntity e){
        Integer goodsNumber = e.getGoodsNumber();
        Long goodsId = e.getGoodsId();
        Integer repositoryId = e.getRepositoryId();

        QueryWrapper<StoreEntity> storeWrapper = new QueryWrapper<>();
        storeWrapper.eq("goods_id", goodsId);
        storeWrapper.eq("repository_id", repositoryId);
        storeWrapper.eq("is_delete", 0);
        StoreEntity storeEntity = storeMapper.selectOne(storeWrapper);

        System.err.println("在addStore中，storeEntity:" + storeEntity);

        if (storeEntity == null) {
            StoreEntity storeEntity1 = new StoreEntity();
            storeEntity1.setIsDelete(0);
            storeEntity1.setGoodsId((Integer) goodsId.intValue());
            storeEntity1.setGoodsNumber(goodsNumber);
            storeEntity1.setRepositoryId(repositoryId);
            System.err.println("storeEntity:" + storeEntity1);
            storeMapper.insert(storeEntity1);
            return 200;
        }


        storeEntity.setGoodsNumber(storeEntity.getGoodsNumber() + goodsNumber);
        storeMapper.updateById(storeEntity);

        return 200;
    }

    /**
     * 新建快速订单
     * @param username
     * @return
     */
    @Override
    public Long newQuick(String username){
        OrderEntity order = new OrderEntity();
        order.setInOut(1);
        order.setIsDelete(0);
        order.setOrderType("Q");
        order.setStatus("草稿");
        order.setClientName("quickClient");
        order.setUsername(username);

        OrderEntity order1 = new OrderEntity();
        order1.setIsDelete(-1);
        mapper.insert(order1);

        QueryWrapper<OrderEntity> qw = new QueryWrapper<OrderEntity>().eq("is_delete", -1);
        OrderEntity curr = mapper.selectList(qw).get(0);

        order.setOrderId(curr.getOrderId());

        mapper.updateById(order);
        return order.getOrderId();


    }
}
